package com.niu.controller;

import com.niu.pojo.Dept;
import com.niu.pojo.MyResult;
import com.niu.service.DeptService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * 部门管理Controller
 */
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    // 获取所有的部门信息
    @GetMapping
    public MyResult<List<Dept>> getList() {
        List<Dept> depts = deptService.getList();
        if (depts == null) {
            return MyResult.error("没有数据");
        }
        return MyResult.ok(depts);
    }

    // 删除部门信息
    @DeleteMapping("/{id}")
    public MyResult<Object> deleteById(@PathVariable Integer id) throws ParseException {
        int i = deptService.deletById(id);
        if (i == 0) {
            return MyResult.error(id + " 号id 删除失败, 请确认");
        }
        return MyResult.ok(i);
    }

    // 添加部门信息
    @PostMapping
    public MyResult<Object> insertDept(@RequestBody Dept dept) {
        int i = deptService.insertDept(dept);
        if (i == 0) {
            return MyResult.error(dept.getName() + " 部门添加失败");
        }
        return MyResult.ok(dept.getId());
    }

    // 根据id 查询部门
    @GetMapping("/{id}")
    public MyResult<Dept> getById(@PathVariable Integer id) {
        Dept dept = deptService.getById(id);
        return dept != null ? MyResult.ok(dept) : MyResult.error("没有 " + id + " 号部门信息");
    }

    // 根据id 更新部门
    @PutMapping
    public MyResult<Object> updateById(@RequestBody Dept dept){
        int i = deptService.updateById(dept);
        return i == 0 ? MyResult.error(dept.getName() + " 更新失败") : MyResult.ok(dept.getName() + " 更新成功");
    }

}
